package math;

/**
 * 一个char类型的数组chs，其中所有的字符都不同。
 * 例如，chs=['A'， 'B', 'c'，... 'z']，则字符串与整数的对应关系如下:A,B... z.AA.AB. ..AZ,BA.BB...ZZ,AAA... zzz.AAAA. . .
 * 1，2...26,27，28... 52,53,54...702,703... 18278,18279.. .例如，chs=['A'， "B'，'C']，则字符串与整数的对应关系如下;A,B.C.AA，AB.. .CC,AAA.. .CCC,AAAA. . .
 * 1，2.3,4,5...12,13...39,40.. .
 * 给定一个数组chs，实现根据对应关系完成字符串与整数相互转换的两个函数。
 *
 * @author Liaorun
 */
public class NumberAndString {

    public static void main(String[] args) {
        char[] chars = new char[26];
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char) ('A' + i);
        }

        String string = getString(chars, 2321);
        System.out.println(string);
        System.out.println(getNum(chars, string));
        System.out.println(getNum(chars, "BAEC"));
    }

    public static String getString(char[] str, int n) {
        if (str == null || str.length == 0) {
            return "";
        }

        int cur = 1;
        int base = str.length;

        int len = 0;
        while (n >= cur) {
            len++;
            n -= cur;
            cur *= base;
        }

        char[] res = new char[len];
        int index = 0;
        int nCur;
        do {
            cur /= base;
            nCur = n / cur;
            res[index++] = getKtnCharAtChs(str, nCur + 1);
            n %= cur;
        } while (index != res.length);

        return String.valueOf(res);
    }

    private static char getKtnCharAtChs(char[] str, int k) {
        if (k < 1 || k > str.length) {
            return 0;
        }
        return str[k - 1];
    }

    public static int getNum(char[] chars, String str) {
        if (chars == null || chars.length == 0) {
            return 0;
        }

        char[] strc = str.toCharArray();
        int base = chars.length;
        int cur = 1;
        int res = 0;
        for (int i = strc.length - 1; i >= 0; i--) {
            res += getNthFromChar(chars, strc[i]) * cur;
            cur *= base;
        }

        return res;
    }

    private static int getNthFromChar(char[] chars, char c) {
        int res = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == c) {
                res = i + 1;
                break;
            }
        }
        return res;
    }
}
